<template>
    <div class="api-example">
        <h2>API 使用示例</h2>

        <!-- 登录示例 -->
        <div class="section">
            <h3>登录测试</h3>
            <van-form @submit="handleLogin">
                <van-field v-model="loginForm.email" name="email" label="邮箱" placeholder="请输入邮箱"
                    :rules="[{ required: true, message: '请填写邮箱' }]" />
                <van-field v-model="loginForm.password" type="password" name="password" label="密码" placeholder="请输入密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit" :loading="loginLoading">
                        登录
                    </van-button>
                </div>
            </van-form>
        </div>

        <!-- AI角色列表示例 -->
        <div class="section">
            <h3>AI角色列表</h3>
            <van-button @click="loadCharacters" :loading="charactersLoading">
                加载角色列表
            </van-button>

            <div v-if="characters.length > 0" class="characters-list">
                <div v-for="character in characters" :key="character.id" class="character-item">
                    <van-card :num="character.difficulty_text" :price="`难度: ${character.difficulty_level}`"
                        :title="character.name" :desc="character.description" :thumb="character.avatar_url">
                        <template #tags>
                            <van-tag v-for="tag in character.tags" :key="tag" type="primary" style="margin-right: 4px;">
                                {{ tag }}
                            </van-tag>
                        </template>
                    </van-card>
                </div>
            </div>
        </div>

        <!-- 用户信息示例 -->
        <div class="section" v-if="userInfo">
            <h3>当前用户信息</h3>
            <van-cell-group>
                <van-cell title="用户名" :value="userInfo.username" />
                <van-cell title="邮箱" :value="userInfo.email" />
                <van-cell title="注册时间" :value="formatDate(userInfo.created_at)" />
            </van-cell-group>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast } from 'vant'
import { authApi, type LoginParams, type User } from '@/api/auth'
import { trainingApi, type AiCharacter } from '@/api/training'

// 响应式数据
const loginForm = ref<LoginParams>({
    email: 'test@example.com',
    password: 'password123'
})

const loginLoading = ref(false)
const charactersLoading = ref(false)
const characters = ref<AiCharacter[]>([])
const userInfo = ref<User | null>(null)

// 登录处理
const handleLogin = async () => {
    try {
        loginLoading.value = true
        const response = await authApi.login(loginForm.value)

        // 保存token和用户信息
        localStorage.setItem('access_token', response.data.access_token)
        localStorage.setItem('user_info', JSON.stringify(response.data.user))

        userInfo.value = response.data.user
        showToast('登录成功')

        // 登录成功后加载用户信息
        await loadCurrentUser()
    } catch (error) {
        console.error('登录失败:', error)
    } finally {
        loginLoading.value = false
    }
}

// 加载当前用户信息
const loadCurrentUser = async () => {
    try {
        const response = await authApi.getCurrentUser()
        userInfo.value = response.data
    } catch (error) {
        console.error('获取用户信息失败:', error)
    }
}

// 加载AI角色列表
const loadCharacters = async () => {
    try {
        charactersLoading.value = true
        const response = await trainingApi.getCharacters()
        characters.value = response.data
        showToast(`加载了 ${response.data.length} 个角色`)
    } catch (error) {
        console.error('加载角色列表失败:', error)
    } finally {
        charactersLoading.value = false
    }
}

// 格式化日期
const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时检查登录状态
onMounted(() => {
    const token = localStorage.getItem('access_token')
    const savedUserInfo = localStorage.getItem('user_info')

    if (token && savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo)
        loadCurrentUser() // 验证token是否有效
    }
})
</script>

<style scoped>
.api-example {
    padding: 16px;
}

.section {
    margin-bottom: 24px;
    padding: 16px;
    background: #f7f8fa;
    border-radius: 8px;
}

.section h3 {
    margin: 0 0 16px 0;
    color: #323233;
}

.characters-list {
    margin-top: 16px;
}

.character-item {
    margin-bottom: 12px;
}
</style>